package com.imooc.controller;

import com.imooc.config.ProjectUrlConfig;
import com.imooc.constant.CookieConstant;
import com.imooc.constant.RedisConstant;
import com.imooc.dataobject.SellerInfo;
import com.imooc.enums.ResultEnum;
import com.imooc.service.SellerService;
import com.imooc.utils.CookieUtilERROR;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

/**?openid=123&username=nnn&password=123
 *校验用户有没有登陆步骤：
 *   1 先从cookie 根据token 取到值，
 *   2 再去Redis 根据 token 查一下值（openid）， 有-已登录
 */
@Controller
@RequestMapping("/seller/auth")
public class SellerLoginAuth {

    @Autowired
    private SellerService sellerService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid,
                              HttpServletResponse response,
                              Map<String, Object> map){

        // 1. 先查询 -- 比对数据 匹配
        SellerInfo sellerInfo = sellerService.findSellerInfoByOpenid(openid);
        if (sellerInfo == null){
            map.put("msg", ResultEnum.LOGIN_FAIL.getMessage());
            map.put("url", "/sell/seller/order/list");
            return new ModelAndView("/common/error",map);
        }

        // 2. 设置token 到 Redis 中
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;

        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_FREFIX,token), openid, RedisConstant.EXPIRE);

        // 3. 将token 设置到 cookie 写到response ---  HttpServletResponse httpServletResponse,
        CookieUtilERROR.set(response, CookieConstant.TOKEN, token, expire);
            // 用绝对地址
        return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list");

        //不能这样写，只进行跳转 ， 不进行模板的渲染。
    }

    // 登出操作
    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request,
                               HttpServletResponse response,
                               Map<String, Object> map) {
        //1. 从cookie里查询
        Cookie cookie = CookieUtilERROR.get(request, CookieConstant.TOKEN);
        if (cookie != null) {
            //2. 清除redis
            redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_FREFIX, cookie.getValue()));

            //3. 清除cookie
            CookieUtilERROR.set(response, CookieConstant.TOKEN, null, 0);
        }

        map.put("msg", ResultEnum.LOGOUT_SUCCESS.getMessage());
        map.put("url", "/sell/seller/order/list");
        return new ModelAndView("common/success", map);
    }

    //  验证失败 -- 去往这个页面重新登陆
    @GetMapping("/relogin")
    public ModelAndView relogin(Map<String, Object> map){
        map.put("msg", "重新登陆");
        return new ModelAndView("/auth/relogin",map);
    }

}
